const blogCommentModel = require('../../model/blogCommentModel')
const db = require('../../config/db')
const {QueryTypes} = require("sequelize");

// 拼接sql查询条件
function joinWhereData(whereData) {
    let where = null
    const whereDataKey = Object.keys(whereData)
    if (whereDataKey.length === 1) {
        if (!whereData[whereDataKey[0]]) {
            where = `${whereDataKey[0]} IS NULL`
        } else {
            if ((typeof whereDataKey[0]) === 'string') {
                where = `${whereDataKey[0]}='${whereData[whereDataKey[0]]}'`
            } else {
                where = `${whereDataKey[0]}=${whereData[whereDataKey[0]]}`
            }
        }
    } else {
        whereDataKey.forEach((i, index) => {
            if (index === 0) {
                if (!whereData[i]) {
                    where = `${i} IS NULL`
                } else {
                    if ((typeof whereData[i]) === 'string') {
                        where = `${i}='${whereData[i]}'`
                    } else {
                        where = `${i}=${whereData[i]}`
                    }
                }
            } else {
                if (!whereData[i]) {
                    where = where + ` and ${i} IS NULL`
                } else {
                    if ((typeof whereData[i]) === 'string') {
                        where = where + ` and ${i}='${whereData[i]}'`
                    } else {
                        where = where + ` and ${i}=${whereData[i]}`
                    }
                }
            }
        })
    }
    return where
}


class BlogCommentSet {
    // 添加评论
    async addBlogComment(CommentData) {
        const data = await blogCommentModel.create(CommentData)
        return data
    }


    // 查询评论列表
    async inquireBlogCommentList(listQuery, whereData) {
        //需要查询的字段
        const searchFields = [
            'blog_comment.id AS id',
            'comment_content AS commentContent',
            'blog_text.blog_title AS blogTitle',
            'blog_users.user_name AS userName',
            'blog_users.user_number AS userNumber',
            'blog_comment.createdAt AS createdAt'
        ]
        // sql语句前部分
        const SQL = `SELECT ${searchFields.join(',')} FROM blog_comment `
        // join部分
        const userJOIN = 'JOIN blog_users ON blog_comment.blog_user_id = blog_users.id '
        const blogTextJOIN = 'JOIN blog_text ON blog_comment.blog_text_id = blog_text.id '
        // 分页部分
        const paging = `LIMIT ${listQuery.limit} OFFSET ${(listQuery.page - 1) * listQuery.limit}`
        //where部分
        let where = ''
        let whereJson = {}
        if (whereData.blog_title && !whereData.user_Name) {
            where = `WHERE blog_text.blog_title = '${whereData.blog_title}'`
        } else if (!whereData.blog_title && whereData.user_Name) {
            where = `WHERE blog_users.user_name = '${whereData.user_Name}'`
        } else if (whereData.blog_title && whereData.user_Name) {
            where = `WHERE blog_text.blog_title = '${whereData.blog_title}' AND blog_users.user_name = '${whereData.user_Name}'`
        } else {
            whereJson = null
            where = ''
        }
        let data = null
        if (where) {
            data = await db.query(SQL + userJOIN + blogTextJOIN + where + paging, null)
        } else {
            data = await db.query(SQL + userJOIN + blogTextJOIN + paging, null)
        }

        const totalSql = 'SELECT COUNT(*) as total FROM blog_comment '
        const total = await db.query(totalSql + userJOIN + blogTextJOIN + where)
        data.total = total[0][0].total
        return data
    }


    //查询评论
    async inquireBlogComment(listQuery, searchData) {
        const searchDataProps = [
            'blog_comment.id AS id',
            'comment_content AS commentContent',
            'blog_text_id AS blogTextId',
            'blog_users.user_name AS userName',
            'blog_users.user_number AS userNumber',
            'blog_users.user_photo_url AS userPhotoUrl',
            'blog_user_id AS blogUserId',
            'parent_id AS parentId',
            'blog_comment.createdAt AS createdAt ',
            'blog_comment.response_times AS responseTimes ',
        ]
        let where = joinWhereData(searchData)
        //分页部分
        const paging = ` ORDER BY blog_comment.updatedAt DESC LIMIT ${listQuery.limit} OFFSET ${(listQuery.page - 1) * listQuery.limit}`

        const sql = `SELECT ${searchDataProps.join(',')} FROM blog_comment LEFT JOIN blog_users ON blog_users.id = blog_comment.blog_user_id  WHERE ${where+paging}`
        const data = await db.query(sql, {type: QueryTypes.SELECT})
        return data
    }

    // 删除评论
    async deleteBlogComment(id) {
        const data = await blogCommentModel.destroy({
            where: {
                id: id
            }
        })

        return data
    }

    //根据日期范围查询
    async getBlogCommentCount(start, end) {
        const sql = `SELECT id FROM blog_comment WHERE createdAt BETWEEN '${start}' AND '${end}'`
        const data = await db.query(sql, {type: QueryTypes.SELECT})
        return data
    }

    async getData(id) {
        const data = await blogCommentModel.findAll({
            where: {
                id: id
            }
        })
        return data
    }

    async updateData(where, updateData) {
        const data = await blogCommentModel.update(updateData, {
            where: where
        })
        return data
    }


}


module.exports = new BlogCommentSet()
